package org.rpc.protocol;

import org.apache.commons.io.IOUtils;
import org.rpc.common.Invocation;
import org.rpc.register.LocalRegister;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class DispatchHandler {
    public void handler(HttpServletRequest req, HttpServletResponse resp) {
        //将req的输入流转换为object的输入流
        Invocation invocation = null;
        try {
            invocation = (Invocation) new ObjectInputStream(req.getInputStream()).readObject();
            //获取到接口名称
            String interfaceName = invocation.getInterfaceName();
            //获取实现类的class
            Class<?> aClass = LocalRegister.get(interfaceName, invocation.getVersion());
            Method method = aClass.getMethod(invocation.getMethodName(), invocation.getParameterTypes());
            //触发方法
            String invoke = (String) method.invoke(aClass.newInstance(), invocation.getParameters());
            //将结果写入到response的输出流里
            IOUtils.write(invoke, resp.getOutputStream());
        } catch (IOException | ClassNotFoundException | InvocationTargetException | IllegalAccessException |
                 NoSuchMethodException | InstantiationException e) {
            throw new RuntimeException(e);
        }

    }
}
